import time
from selenium import webdriver
from selenium.common import WebDriverException, InvalidArgumentException, NoSuchElementException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from functions import open_browser


# 初始化浏览器
class Base:
    def __init__(self, browser):
        self.driver = browser

    def get(self, url):
        try:
            self.driver.get(url)
        except(InvalidArgumentException, WebDriverException):
            print('输入网址不正确')

    # 元素定位
    def find_element(self, locator, timeout=5):  # locator 元组
        try:
            return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator))
        except TimeoutException:
            print("元素定位失败")

    def click(self, locator):
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print("元素定位失败")

    def send_keys(self, locator, value):
        element = self.find_element(locator)
        if element is not None:
            element.send_ksys()
        else:
            print("写入失败")

    def back(self):
        self.driver.back()

    def refresh(self):
        self.driver.refresh()

    def close(self):
        self.driver.close()

    def forward(self):
        self.driver.forward()

    # 获取元素属性
    def get_attrbute(self, locator, value):
        element = self.find_element(locator)
        if element:
            return element.get_attribut(value)
        else:
            print("元素定位失败")

    def get_element_text(self, locator):
        # 获取元素文本
        element = self.find_element(locator)
        if element:
            return element.text

    def quit(self, seconds=3):
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    browser = open_browser()
    base = Base(browser)
    base.get("https://www.baidu.com")
    kw = base.find_element((By.ID, "kw"), 3)
    print(kw.get_attribute("outerHTML"))
    base.quit()
